package com.demo.service_admin.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.demo.dao_admin.CourseDAO;
import com.demo.entity.Course;
import com.demo.service_admin.CourseService;

@Service("adminCourseService")
@Transactional
public class CourseServiceImpl implements CourseService {
	
	@Resource(name="adminCourseDAO")
	CourseDAO courseDAO;
	
	@Override
	public Page<Course> findAll(Course course, Pageable pageable) {		
		/**
		 * Path、Predicate同为Expression子接口，前者代表查询的实体属性，后者代表一个查询条件
		 */
		Specification<Course> spec = new Specification<Course>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<Course> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				/**
				 * root:要查询的实体
				 * query:一条查询语句
				 * cb:查询语句构造器
				 */
				Path<Object> teacherIdPath = root.get("teacherId");//构造Path,等同于SQL 取某张表的某个字段
				Path<Object> onstatePath = root.get("onstate");
				Path<Object> courseNamePath = root.get("courseName");
				
				List<Predicate> predicates = new ArrayList<>();//构造List,保存所有Predicate,每一个Predicate就是一个查询条件，相当于where 条件表达式1【字段= like值】 and 条件表达式2
				
				if(null != course.getTeacherId()) {//传入参数不为空，则添加一个查询条件
					Predicate predicate = cb.equal(teacherIdPath, course.getTeacherId());//构造一个精确匹配
					predicates.add(predicate);
				}
				
				if(null != course.getOnstate()) {
					Predicate predicate = cb.equal(onstatePath, course.getOnstate());
					predicates.add(predicate);
				} //如果前端传入的查询条件含有teacherId以及onstate，那么，此时构造的sql语句就是 from Course where teacherId=?1 and onstate=?2 and courseName like '%?3%'
				
				if(StringUtils.isNotEmpty(course.getCourseName())) {
					Predicate predicate = cb.like(courseNamePath.as(String.class), "%"+course.getCourseName()+"%");//构造一个like搜索条件
					predicates.add(predicate);
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));// 把所有查询条件用and拼接

			}
		};
		//调用DAO组件传入specification执行动态查询
		Page<Course> list = courseDAO.findAll(spec, pageable);
		return list;
	}

	@Override
	public Course findById(Long id) {
		return courseDAO.findById(id).get();
	}

}
